import axios from 'axios'
import ItemIcon from './ItemIcon'
import input from './control/Input'
import checkbox from './control/CheckBox'
import radio from './control/Radio'
import select from './control/Select'
import textarea from './control/Textarea'
import uploads from './control/Uploads'
import datetime from './control/DateTime'
import category from './control/Category'

const form_item = {
	input,
	textarea,
	select,
	radio,
	checkbox,
	uploads,
	datetime,
	category
};

export default {
	render(h) {
		// 获取当前控件渲染
		const arr = (form_item[this.conf.type] && form_item[this.conf.type](this, h)) || [];
		// 显示配置按钮并且控件允许被配置
		const item_icon = this.configIcon && this.conf.config ? ItemIcon(this, h) : [];
		// 已被绑定field,且require为必填,视为校验字段
		const validate = !!this.conf.field && !!this.conf.require;
		// 非 Title Hr P 需要FormItem
		let FormItem = {
			props: {
				single : (
					'textarea' == this.conf.type || 
					this.conf.multiple == true || 
					('radio' == this.conf.type && this.conf.datas.length > 3)
				) ? true : false,
				label: this.conf.name,
				// 指定验证field
				prop: this.conf.field || 'temp',
				// 验证规则
				rules: {
					required: validate,
					message: '该项为必填项',
					validator: (rule, value, callback) => {
						// 没有配置按钮并且允许验证
						if (!this.configIcon && validate && (Array.isArray(value) ? !value.length : !value)) {
							callback(new Error('该项为必填项'));
						} else {
							callback();
						}
					}
				},
			}
		};
		return h(
			"FormItem", FormItem,
			arr.concat(item_icon)
		);
	},
	mounted() {
		if(this.conf.type == 'radio' || this.conf.type == 'checkbox' || this.conf.type == 'select'){
			if(!this.conf.datas || this.conf.datas.length == 0){
				this.conf.datas = [{id:1,name:'数据1'},{id:2,name:'数据2'},{id:3,name:'数据3'}]
			}
		}
	},
	methods: {
		//异步
		async getJson(resolve) {
			if(this.conf.url){
				let datas = await this.$global.http('GET',this.conf.url)
				resolve(datas)
			}else{
				let datas = [
					{id:1,name:'浙江',children:[
						{id:10,name:'杭州',children:[
							{id:101,name:'西湖区'},
							{id:102,name:'余杭区'}
						]},
						{id:11,name:'金华',children:[
							{id:111,name:'义乌市'},
							{id:112,name:'东阳市'}
						]}
					]},
					{id:2,name:'江苏',children:[
						{id:20,name:'苏州',children:[
							{id:201,name:'姑苏区'},
							{id:202,name:'昆山市'}
						]},
						{id:21,name:'扬州',children:[
							{id:211,name:'高邮市'},
							{id:212,name:'广陵区'}
						]}
					]}
				]
				setTimeout(()=>{resolve(datas)},1)
			}
		}
	},
	props: {
		// 当前控件的index,config 和 delete 会用到
		index: {
			type: Number,
			default: 0
		},
		// 当前控件的配置
		conf: {
			type: Object,
			default () {
				return {};
			}
		},
		// 是否显示配置按钮
		configIcon: {
			type: Boolean,
			default: false
		},
		// 当前控件绑定的值 方便数据回填
		value: [String, Number, Array]
	}
}